import request from '@/utils/request';
import appConfig from '@/utils/appConfig';
import Taro from '@tarojs/taro';
import { PlatformEnum } from '@/utils/enum';


/**
 * 小程序登录凭证校验接口（V1）
 *
 * @param data.code 微信登录凭证
 * @param data.businessMerchantAppConfigId 商户应用配置ID
 * @returns 返回请求结果
 */
export async function wechatCode2SessionV1(data: { code: string }): Promise<{accessToken: string}> { 
  const configData = {'AppConfigId': appConfig.appConfigId, 'SmallAppId': appConfig.smallAppId,'MerchantId': appConfig.merchantId};
  const postData =  {...data, ...configData}
  return request({ url: process.env.TARO_ENV === 'weapp'? '/api/Wechat/Login' : '/api/Douyin/Login', data: postData, method: 'post'})
}

/**
 * 将微信公共平台获取的code转换成sessionKey
 *
 * @param data 包含code和businessMerchantAppConfigId的对象
 * @returns 返回请求结果
 */
export async function weChatPubCode2SessionV1(code: string): Promise<{ accessToken: string }> {
    return request({
        url: '/api/WeChatPub/Login',
        method: 'post',
        data: {
            code,
            merchantId: appConfig.merchantId,
            smallAppId: appConfig.smallAppId,
            appConfigId: appConfig.appConfigId,
        },
    });
    // return request({ url: '/api/WeChatPub/Code2SessionV1', data })
}


// 微信绑定手机号
export async function getPhoneByCode(code: string): Promise<User.PhoneInfo> {
  return request({url:`/api/Wechat/BindUser`,method:'post',data:{code}})
}


// 获取影院城市
export async function getAddress(): Promise<{
    list: {
        cityCode: string;
        city: string;
        initial: string;
    }[];
}> {
    return request('/api/Movie/GetMovieCities');
}

/**
 * @description 获取电影城市列表
 */
export function getMovieCityList(): Promise<{ list: City.List[] }> {
    return request.get(`/api/Movie/GetMovieCities`);
}

// 获取微信分享配置
export async function getWxConfig(): Promise<{
    appId: string;
    timestamp: number;
    nonceStr: string;
    signature: string;
}> {
    let shareUrl = '';
    if (process.env.TARO_ENV === 'h5') {
        shareUrl = /(Android)/i.test(navigator.userAgent)
            ? window.location.href
            : // @ts-ignore
              window.entryUrl;
    }
    return request({
        url: '/api/WeChatPub/GetWeChatShareConfig',
        method: 'post',
        data: {
            shareUrl,
            merchantId: appConfig.merchantId,
            smallAppId: appConfig.smallAppId,
            appConfigId: appConfig.appConfigId,
        },
    });
}

// 热门影片
export function getHotMovies(pageSize?: number): Promise<{ list: Movie.MovieItem[] }> {
    return request.get(`/api/Movie/GetHotMovies`, { params: pageSize ? { pageSize } : {} });
}

// 待上映影片
export function getUpcomingMovies(pageSize?: number): Promise<{ list: Movie.MovieItem[] }> {
    return request.get(`/api/Movie/GetUpcomingMovies`, { params: pageSize ? { pageSize } : {} });
}

//
export async function getProductInfoById(id: React.Key): Promise<any> {
    return request(`/api/Default/GetJumpProductInfo/${id}`);
}

// 获取当前用户的cps配置
export function getUserCpsSetting() {
    return request('/api/CpsSetting/GetCpsSettingPageList');
}

/**
 * @description 获取影院信息
 */
export function getMovieCinemaInfo(params: {
    cinemaId: string | undefined;
    cityId?: string;
    longitude?: string | number;
    latitude?: string | number;
}): Promise<Movie.CinemaItem> {
    return request.get('/api/Movie/GetMovieCinemaInfo', { params });
}

export function getCinemaList(params: {
    // radius?: string | number;
    cityId?: string | number;
    longitude?: string | number;
    latitude?: string | number;
    couponCode?: string | undefined;
}): Promise<Movie.CinemaItem> {
    return request.get('/api/Movie/GetNearbyCinemas', { params });
}

/**
 * @description 获取观影日期
 */
export function getMovieShowDate(params: {
    filmId: string;
    cityId: number | undefined;
}): Promise<Omit<Movie.MovieItem, 'intro'>> {
    return request.get('/api/Movie/GetMovieShowDate', { params });
}

/**
 * @description 获取电影所属影院
 */
export function getMovieCinemaList(params: {
    filmId: string;
    cityId: number | undefined;
    movieShowTime: string;
    longitude?: string | number;
    latitude?: string | number;
}): Promise<{ list: Movie.CinemaItem[] }> {
    ///api/Movie/GetCinemaMovieSchedules
    return request.get('/api/Movie/GetCinemas', { params });
}

export enum UsedEnum {
    unUse = 0,
    used = 1,
    expire = 2,
}

getUserBenefitCardList.filterEnum = UsedEnum;
export async function getUserBenefitCardList(params: { filterType: UsedEnum }): Promise<{
    list: Combination.Item[];
}> {
    return request.get(`/api/Coupon/GetUserBenefitCardList`, { params });
}

getUserCouponList.filterTypeEnum = UsedEnum;
export async function getUserCouponList(params: {
    cinemaCode?: number | string;
    moveCode?: number | string;
    hall?: string;
    showTime?: string;
    showId?: string;
    version?: string;
    originPrice?: number;
    publishPrice?: number;
    buyNum?: number;
}): Promise<{
    list: Coupon.ListItem[];
}> {
    return request.get(`/api/Coupon/GetUserCouponList`, { params });
}

/**
 * @description 获取验证码
 */
export async function getCode(mobile: string) {
    let url = '/api/H5/SendMobileVerificationCode';
    if (process.env.TARO_ENV !== 'h5' || appConfig.appPlatformType === 4) {
        url = '/api/User/SendMobileVerificationCode';
    }
    return request({
        url: url,
        method: 'post',
        data: {
            mobile,
            AppConfigId: appConfig.appConfigId,
            SmallAppId: appConfig.smallAppId,
            MerchantId: appConfig.merchantId,
        },
    });
}

/**
 * @description 绑定手机号
 */
export async function updateUserPhone(data: { mobile: string; verifyCode: string }) {
    return request({
        url: '/api/User/BindUser',
        method: 'post',
        data: { mobile: data.mobile, verifyCode: data.verifyCode },
    });
}

/**
 * @description 手机号登录
 */

export async function loginWithCode(data: { mobile: string; verifyCode: string }) {
    const configData = {
        AppConfigId: appConfig.appConfigId,
        SmallAppId: appConfig.smallAppId,
        MerchantId: appConfig.merchantId,
    };
    const postData = { ...data, ...configData };

    let url = '/api/H5/Login';
    return request({
        url: url,
        method: 'post',
        data: postData,
    });
}

/**
 * @description 获取订单列表
 */

export async function getUserMovieOrders(params: {
    orderStatus?: string;
    multiOrderStatus?: string;
    pageSize?: number;
    pageIndex?: number;
}): Promise<API.List<Order.MovieOrderItem>> {
    return request.get('/api/Order/GetMovieOrders', { params });
}

export async function submitOrder(
    orderNo: string,
    deviceType = 1,
    orderType = 1
): Promise<{
    payParameter: string;
}> {
    //  1：小程序， 2：支付宝，3：h5,4：公众号
    if (process.env.TARO_ENV == 'h5') {
        deviceType = 4;
    }
    if (Taro.getStorageSync('platform') == 'yzfapp') {
        deviceType = 3;
    }
    return request({
        url: '/api/Order/CreatePaymentOrder',
        method: 'post',
        data: {
            businessMerchantAppConfigId: appConfig.businessMerchantAppConfigId,
            orderNo,
            deviceType,
            orderType: orderType,
            paymentMethodId: 1, // todo 动态获取
            paymentScene:
                appConfig.appPlatformType === PlatformEnum.WeChatPub ? '' : process.env.TARO_ENV,
            //paymentMethodId 支付方式编号 integer($int32)
            QuitUrl: `${window.location.origin}/pages/order/detail/index?orderNo=${orderNo}`,
        },
    });
}

/**
 * @description 获取电影票订单详情
 */
export function getOrderDetailByCoupon(
    couponCode: string
): Promise<Movie.Order.MovieOrderResponse> {
    return request.get(`/api/Movie/GetOrderDetailByCoupon/${couponCode}`);
}

/**
 * @description 获取电影票订单详情
 */
export function getOrderDetail(orderNo: string): Promise<Movie.Order.MovieOrderResponse> {
    return request.get(`/api/Order/GetMovieOrder?orderNo=${orderNo}`);
}

/**
 *
 * @description 取消电影订单
 *
 */
export async function orderCancel(params: { orderNo: string }) {
    return request.post(`/api/Order/CancelMovieOrder`, params);
}

/**
 * @description 获取影院播放电影
 */
export function getCinemaMovieList(params: {
    storeId: string;
    couponCode?: string;
}): Promise<{ list: Movie.CinemaMovieItem[] }> {
    return request.get('/api/Movie/GetCinemaMovies', { params });
}

/**
 * @description 获取电影影院排片
 */
export function getMovieCinemaScheduleList(params: {
    storeId: string | number;
    movieShowTime: string;
    filmId: string | number;
    cityId: number | undefined;
}): Promise<{ list: Movie.TheaterItem[] }> {
    return request.get('/api/Movie/GetCinemaMovieSchedules', { params });
}

/**
 * @description 旁边座位不要留空 - 校验
 */
export function isLeaveNextSeatsEmpty(params: {
    filmId: string; //电影编码
    storeId: string; //影院编号
    showId: string; //场次编号
    seatItems?: {
        columnNo: string; //座位坐标，列
        rowNo: string; //座位坐标，排。
        seatName: string; //座位名 放单需要取此字符串中的排和座，建议使用正则。某些影院会出现 ”A排B座” ”3行4列” "1排12座"，参考放单接
    }[];
}): Promise<Movie.CheckSeatResponse> {
    return request.post('/api/Movie/CheckScheduleSeats', params);
}

/**
 * @description 获取电影影院排片座位
 */
export function getMovieCinemaScheduleSeat(params: {
    showId: string;
    filmId: string | number;
    storeId: any;
    isvId: string;
}): Promise<Movie.CinemaScheduleSeat> {
    return request.get('/api/Movie/GetScheduleSeats', { params });
}

/**
 * @description 获取用户联系手机号
 */
export async function getUserContactMobile(): Promise<string> {
    return request.get('/api/Default/GetUserContactMobile');
}

/**
 * @description 创建电影票订单
 */

export function movieCreateOrder(
    params: {
        isvId?: number;
        fastTicket?: boolean;
        mobile: string;
        cinemaCode: string;
        moveCode: string;
        showId: string;
        switchSeat: boolean;
        comeFrom?: string;
        channel?: string;
        seatItems?: {
            columnNo: string; //座位坐标，列
            rowNo: string; //座位坐标，排。
            seatName: string; //座位名 放单需要取此字符串中的排和座，建议使用正则。某些影院会出现 ”A排B座” ”3行4列” "1排12座"，参考放单接
        }[]; //座位
        couponCode?: string;
    },
    type?: string
): Promise<any> {
    // 代理商创建电影票订单
    const url =
        type === 'open' ? '/api/Order/CreateAgencyMovieOrder' : '/api/Order/CreateMovieOrder';
    if (type === 'open') {
        params.fastTicket = false;
    }

    return request.post(url, params);
}
